package com.zjt.smart.mvp.presenter.base;

import android.text.TextUtils;

import com.google.gson.JsonSyntaxException;
import com.zjt.smart.api.server.BaseServer;
import com.zjt.smart.mvp.view.LoadView;

import java.util.List;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Response;

/**
 * <p>Title: </p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2017</p>
 * <P>Company: </p>
 *
 * @author zhengjianting
 * @time 2017/8/29 0029 上午 10:57
 */

public abstract class ResponseCallback<DataType> extends BaseCallback{
    private static final String TAG = "ResponseCallback";
    protected LoadView<DataType> mLoadView;
    protected BaseServer mServer;
    protected Call<DataType> mCall;

    public ResponseCallback(Call mCall, LoadView<DataType> mLoadView, BaseServer mServer) {
        this.mCall = mCall;
        this.mLoadView = mLoadView;
        this.mServer = mServer;
    }

    @Override
    public void onLoadCache(long cacheTime, String cacheStr) {
        if (mCall == null || mCall.isCanceled()){
            return;
        }
        if (TextUtils.isEmpty(cacheStr)) {
            mLoadView.onCache(0, null);
            return;
        }

        List<DataType> list = parseResult(cacheStr);
        mLoadView.onCache(cacheTime, list);
    }

    @Override
    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
        if (mCall == null || mCall.isCanceled()){
            return;
        }
        if (!response.isSuccess()) {
            mLoadView.onFail(response.code(), "At " + TAG + "#onResponse-> " + response.errorBody().toString());
            return;
        }

        try {
            String jsonStr = response.body().string();
            List<DataType> list = parseResult(jsonStr);
            if (list == null || list.size() == 0){
                mLoadView.onFail(mServer.NO_MORE, "At " + TAG + "#onResponse-> No More");
                return;
            }
            mLoadView.onSuccess(list);

        } catch (JsonSyntaxException e) {
            e.printStackTrace();
            mLoadView.onFail(mServer.PARSE, "At " + TAG + "#onResponse-> Parse Error");
        } catch (Exception e) {
            e.printStackTrace();
            // Can't Find Object.
            mLoadView.onFail(mServer.SYNTAX, "At " + TAG + "#onResponse-> Can't Find Object.Because JSONNull");
        }

    }

    protected abstract List<DataType> parseResult(String result);

    @Override
    public void onFailure(Call<ResponseBody> call, Throwable t) {
        if (mCall == null || mCall.isCanceled()){
            return;
        }
        mLoadView.onFail(BaseServer.SYNTAX, "At " + TAG + "#onFailure-> " + t.toString());
    }
}
